package com.java.eight.lambda;

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;

/**
* @description: lambda表达式方法推导
* @author: xiaoliang.liu
* @date: 2018/7/8 14:48
* @version v1.0
*/
public class MethodReference {

    public static void main(String[] args) {
//        // 方式一
//        Consumer<String> consumer = (s) -> System.out.println(s);
//        userConsumer(consumer, "hello alex1");
//
//        // 方式二
//        userConsumer(s -> System.out.println(s), "hello alex2");
//
//        // 方式三(类型推导)
//        userConsumer(System.out::println, "hello alex3");
//
//
        // 排序(按照字典顺序)
        List<Apple> apples = Arrays.asList(new Apple("yellow", 15L), new Apple("green", 25L), new Apple("red", 15L));
        System.out.println(apples);
//        apples.sort((a1, a2) -> a1.getColor().compareTo(a2.getColor()));
//        System.out.println(apples);
        // 使用类型推导
        apples.sort(Comparator.comparing(Apple::getColor));
        System.out.println(apples);
//
//        // 使用流遍历数组
//        apples.stream().forEach(a -> System.out.println(a));
//        // 更简洁
//        apples.forEach(System.out::println);
//
//
//        int i = Integer.parseInt("123");
//        // 静态方法的类型推导
//        Function<String, Integer> result = Integer::parseInt;
//        Integer apply = result.apply("456");
//        System.out.println(i + " " + apply);
//
            // 通过类方法
//        BiFunction<String, Integer, Character> biFunction = String::charAt;
//        Character nihao = biFunction.apply("nihao", 2);
//        System.out.println(nihao);
//
//          // 通过对象方法
//        String world = new String("world");
//        Function<Integer, Character> function = world::charAt;
//        Character apply = function.apply(4);
//        System.out.println(apply);

        // 通过构造器
        Supplier<String> supplier = String::new;
        String s = supplier.get();
        System.out.println(s.getClass());

        // 通过构造器(多个构造参数，会自动找到对应参数个数的构造方法)
        BiFunction<String, Long, Apple> appleFunction =  Apple::new;
        Apple redApple = appleFunction.apply("red", 15L);
        System.out.println(redApple);

        // 使用自定义的Function
        ThreeFunction<String, Long, String, ComplexApple> customFunction = ComplexApple::new;
        ComplexApple apply = customFunction.apply("blue", 10L, "蓝苹果");
        System.out.println(apply);


    }


    private static <T> void userConsumer(Consumer<T> consumer, T t) {
        consumer.accept(t);
        consumer.accept(t);
    }




}
